package com.example.springboot_shiro.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @author: lqy
 * @date: 2021/9/10 11:53
 * @description:
 */
@Configuration
@MapperScan(basePackages = TtttDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "ttttSqlSessionFactory")
public class TtttDataSourceConfig {
    /**
     * 配置多数据源 关键就在这里 这里配置了不同的数据源扫描不同mapper
     */
    static final String PACKAGE = "com.example.springboot_shiro.mapper.tttt";
    static final String MAPPER_LOCATION = "classpath*:mybatis/tttt/mapper/*.xml";

    /**
     * 连接数据库信息 这个其实更好的是用配置中心完成
     */
    @Value("${tttt.datasource.url}")
    private String url;

    @Value("${tttt.datasource.username}")
    private String username;

    @Value("${tttt.datasource.password}")
    private String password;

    @Value("${tttt.datasource.driver-class-name}")
    private String driverClassName;

    @Bean("ttttDataSource")
    public DataSource TtttDataSource() {

        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setDriverClassName(driverClassName);
        return dataSource;
    }

    @Bean(name = "ttttTransactionManager")
    public DataSourceTransactionManager masterTransactionManager() {
        return new DataSourceTransactionManager(TtttDataSource());
    }

    @Bean(name = "ttttSqlSessionFactory")
    public SqlSessionFactory masterSqlSessionFactory(@Qualifier("ttttDataSource") DataSource masterDataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(masterDataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(TtttDataSourceConfig.MAPPER_LOCATION));

        return sessionFactory.getObject();
    }
}
